import httpx
from bs4 import BeautifulSoup
import os # 文件创建模块

def download_mp3(client,title,url):
    html=client.get(url)
    play_url=html.json()['data']['play_url']
    if not os.path.exists('./mp3'):
        os.mkdir('./mp3')

    with open(f'./mp3/{title}.mp3', 'wb') as f:
        f.write(client.get(play_url).content)



def index(client):
    index_html='https://www.kugou.com/yy/html/rank.html'
    html1=client.get(index_html)
    soup=BeautifulSoup(html1.text,'lxml')
    data_flag=soup.select('div.pc_temp_songlist.pc_rank_songlist_short ul li')
    for eid in data_flag:
        data_eid=eid['data-eid']
        title=eid['title']
        print(title,data_eid)
        mp3_url=f'https://wwwapi.kugou.com/yy/index.php?r=play/getdata&encode_album_audio_id={data_eid}'
        download_mp3(client,title,mp3_url)

def main():
    headers={
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.54',
        'cookie': 'kg_mid=ea3b321c894d74b76b67e48b2058b1b0; Hm_lvt_aedee6983d4cfc62f509129360d6bb3d=1671683830; kg_dfid=08xnIG0VjAdG2L0f2t2WkE9j; kg_dfid_collect=d41d8cd98f00b204e9800998ecf8427e; kg_mid_temp=ea3b321c894d74b76b67e48b2058b1b0; Hm_lpvt_aedee6983d4cfc62f509129360d6bb3d=1671684384',
        'referer': 'https://www.kugou.com/'
    }
    client = httpx.Client(headers=headers)
    index(client)

if __name__ == '__main__':
    main()